<template>
    <div>
        <div class="mb-8">
            <div>
                <el-button @click="genAll">生成</el-button>
                <el-button
                    type="primary"
                    icon="el-icon-check"
                    v-if="data.some((item) => item.isChanged)"
                >
                    保存
                </el-button>
            </div>
        </div>
        <div class="mb-4 flex">
            <div class="w-[150px] mr-8">触发时机</div>
            <div class="w-[200px] mr-8">
                知识点
                <el-button
                    class="ml-2"
                    size="small"
                    @click="genAllQuestionPoint"
                    >生成知识点</el-button
                >
            </div>
            <div class="flex-1">问题</div>
            <div>
                操作<el-button
                    class="ml-2"
                    size="small"
                    @click="genAllQuestion"
                >
                    生成问题
                </el-button>
            </div>
        </div>
        <div v-for="(item, index) in data" :key="index" class="mb-4 flex">
            <div class="w-[150px] mr-8">
                <div>{{ item.trigger }}</div>
                <div>{{ events[item.trigger] }}</div>
            </div>
            <div class="w-[200px] mr-8">
                <el-input type="textarea" autosize v-model="item.point" />
                <el-button
                    @click="questionPointGen(index)"
                    :loading="item.pointLoading"
                    size="small"
                >
                    重新生成
                </el-button>
            </div>
            <div class="flex-1">
                <div>{{ item.content }}</div>
                <el-skeleton
                    v-if="!item.content && item.loading"
                    :rows="5"
                    style="width: 300px"
                    animated
                >
                    <template #template>
                        <el-skeleton-item variant="text" />
                    </template>
                </el-skeleton>
                <div v-for="(option, index) in item.options" :key="index">
                    {{ option.id }}. {{ option.content }}
                </div>
                <el-skeleton
                    v-if="!item.options.length && item.loading"
                    :rows="5"
                    style="width: 500px"
                    animated
                >
                    <template #template>
                        <el-skeleton-item variant="text" class="w-1/2" />
                        <el-skeleton-item variant="text" />
                        <el-skeleton-item variant="text" class="w-1/3" />
                    </template>
                </el-skeleton>
                <el-skeleton
                    v-if="!item.answer && item.loading"
                    :rows="5"
                    style="width: 240px"
                    animated
                >
                    <template #template>
                        <el-skeleton-item variant="text" />
                    </template>
                </el-skeleton>
                <div v-if="item.answer">正确答案：{{ item.answer }}</div>
            </div>
            <div class="self-center">
                <el-button
                    @click="questionGen(index)"
                    :loading="item.loading"
                    icon="el-icon-refresh"
                >
                    重新生成
                </el-button>
                <el-button
                    v-if="item.isChanged && !item.loading"
                    type="primary"
                    icon="el-icon-check"
                    @click="save(index)"
                >
                    保存
                </el-button>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { chat } from '@/apis/chat'
import { add, getList, update } from '@/apis/commonCrud'
import { getEventsImport } from '@/utils/tcFolderGlob'
import { ElMessage } from 'element-plus'
import { jsonrepair } from 'jsonrepair'
import { ref, watch } from 'vue'

const props = defineProps<{
    teachCaseId: string
    teachCaseKey?: string
    teachCaseTitle?: string
}>()

interface IQuestion {
    teachCaseId: number
    type: 'singleChoice'
    trigger: string
    point: string
    content: string
    options: {
        content: string
        id: string
    }[]
    answer: string
}

interface IQuestionGen extends IQuestion {
    id?: number
    triggerName: string
    isChanged: boolean
    loading?: boolean
    pointLoading?: boolean
}

const data = ref<IQuestionGen[]>([])

const events = ref<any>({})

const getData = async () => {
    if (!props.teachCaseId || !props.teachCaseKey) return
    const res = await getList<{ rows: IQuestion[]; count: number }>(
        'questions',
        { teachCaseId: props.teachCaseId },
        [
            {
                model: 'teachCases',
                attributes: ['id', 'title', 'key'],
                as: 'teachCase',
            },
        ]
    )
    if (!res.success) {
        return
    }
    const eventFunc = getEventsImport(props.teachCaseKey)
    if (!eventFunc) return
    const m = (await eventFunc()) as any
    if (m.EVENTS) {
        events.value = m.EVENTS
    }

    const tempEvents = Object.keys(m.EVENTS).map((k) => {
        return {
            key: k,
            value: m.EVENTS[k],
            used: false,
        }
    })
    const result: IQuestionGen[] = []
    // 已有的题目
    res.data.rows.forEach((item) => {
        const eventIndex = tempEvents.findIndex((e) => e.key === item.trigger)
        const res: IQuestionGen = {
            ...item,
            triggerName: tempEvents[eventIndex].value,
            isChanged: false,
        }
        tempEvents[eventIndex].used = true
        result.push(res)
    })
    tempEvents.forEach((e) => {
        if (!e.used) {
            result.push({
                teachCaseId: Number(props.teachCaseId),
                type: 'singleChoice',
                trigger: e.key,
                point: '',
                content: '',
                options: [],
                answer: '',
                triggerName: e.value,
                isChanged: false,
            })
        }
    })
    data.value = result
}

watch(
    () => props.teachCaseKey,
    (value) => {
        if (value) {
            getData()
        }
    }
)

// 知识点生成
const questionPointGen = async (index: number) => {
    const item = data.value![index]
    if (!item) return
    item.point = ''
    item.isChanged = true
    item.pointLoading = true
    return new Promise((resolve) => {
        chat(
            {
                user: `案例标题：${props.teachCaseTitle}
触发时机：${item.trigger}
触发时机名称：${item.triggerName}`,
            },
            (str) => {
                item.point += str
                // console.log(str)
            },
            'questionPointGen',
            () => {
                item.pointLoading = false
                resolve(true)
            }
        )
    })
}

const genAllQuestionPoint = async () => {
    data.value!.forEach((_item, index) => {
        questionPointGen(index)
    })
}

// 问题生成
const questionGen = async (index: number) => {
    const item = data.value![index]
    if (!item) return
    // item.point = ''
    item.content = ''
    item.options = []
    item.answer = ''
    item.isChanged = true
    item.loading = true
    let res = ''
    return new Promise((resolve) => {
        chat(
            {
                user: `案例标题：${props.teachCaseTitle}
知识点：${item.point}`,
            },
            (str) => {
                // item.point += str
                res += str
                try {
                    const repaired = jsonrepair(res)

                    const parsed = JSON.parse(repaired)

                    if (parsed.content) {
                        item.content = parsed.content
                    }
                    if (parsed.options) {
                        item.options = parsed.options
                    }
                    if (parsed.answer) {
                        item.answer = parsed.answer
                    }
                } catch (err) {
                    console.error(err)
                }
            },
            'questionGen',
            () => {
                item.loading = false
                resolve(true)
            }
        )
    })
}

const genAllQuestion = async () => {
    data.value!.forEach((_item, index) => {
        questionGen(index)
    })
}

const genAll = async () => {
    data.value!.forEach((_item, index) => {
        questionPointGen(index).then(() => {
            questionGen(index)
        })
    })
}

const save = async (index: number) => {
    const item = data.value![index]
    if (!item) return

    const id = item.id
    if (id) {
        const res = await update('questions', id, item)
        if (!res.success) {
            ElMessage.error('保存失败')
            return
        }
        item.isChanged = false
    } else {
        const res = await add('questions', item)
        if (!res.success) {
            ElMessage.error('保存失败')
            return
        }
        // console.log(res)
        item.id = res.data.id
        item.isChanged = false
    }
}
</script>

<style scoped></style>
